﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Skugo.StandardPlugins
{
    /// <summary>
    /// Interaction logic for CommandSearch.xaml
    /// </summary>
    public partial class CommandSearch : Window
    {
        private CommandManager Manager;

        public CommandSearch(CommandManager manager)
        {
            InitializeComponent();

            this.Manager = manager;

            this.RebuildCommands(String.Empty);
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            this.Search.Focus();
        }

        private void Commands_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            var element = (CommandUIElement)this.Commands.SelectedItem;

            element.ExpandTooltip.IsExpanded = e.Key == Key.Right;

            if (e.Key == Key.Up && this.Commands.SelectedIndex == 0)
            {
                this.Search.Focus();
            }
        }

        private void Search_TextChanged(object sender, TextChangedEventArgs e)
        {
            this.RebuildCommands(this.Search.Text);
        }

        private static Int32 GetFilterPriority(String filter, String name)
        {
            if (filter == String.Empty)
            {
                return 1;
            }

            StringBuilder capsBuilder = new StringBuilder();

            foreach (var c in name)
            {
                if (Char.IsUpper(c))
                {
                    capsBuilder.Append(Char.ToLower(c));
                }
            }

            var caps = capsBuilder.ToString();
            var lowerFilter = filter.ToLower();

            if (lowerFilter == caps)
            {
                return 2;
            }

            if (name.ToLower().Contains(lowerFilter))
            {
                return 1;
            }

            return 0;
        }

        private void RebuildCommands(String filter)
        {
            this.Commands.Items.Clear();
            this.Tags.Items.Clear();

            var commandsInOrder = new List<Tuple<Int32, Command>>();

            foreach (var command in this.Manager.Commands.Values)
            {
                var priority = GetFilterPriority(filter, command.Name);

                if (priority > 0)
                {
                    var pair = new Tuple<Int32, Command>(priority, command);
                    commandsInOrder.Add(pair);
                }
            }

            commandsInOrder.Sort((a, b) =>
            {
                if (a.Item1 == b.Item1)
                {
                    return a.Item2.Name.CompareTo(b.Item2.Name);
                }

                return a.Item1.CompareTo(b.Item1);
            });

            foreach (var pair in commandsInOrder)
            {
                var commandElement = new CommandUIElement(pair.Item2, this);
                commandElement.CommandName.Text = pair.Item2.Name;
                this.Commands.Items.Add(commandElement);
            }

            if (this.Commands.Items.Count > 0)
            {
                this.Commands.SelectedIndex = 0;
            }

            var tagsInOrder = new List<Tuple<Int32, String>>();

            var allTags = new HashSet<String>();

            foreach (var command in this.Manager.Commands.Values)
            {
                foreach (var tag in command.Keywords)
                {
                    if (allTags.Contains(tag) == false)
                    {
                        var priority = GetFilterPriority(filter, tag);

                        if (priority > 0)
                        {
                            var pair = new Tuple<Int32, String>(priority, tag);
                            tagsInOrder.Add(pair);
                        }

                        allTags.Add(tag);
                    }
                }
            }

            tagsInOrder.Sort((a, b) =>
            {
                if (a.Item1 == b.Item1)
                {
                    return a.Item2.CompareTo(b.Item2);
                }

                return a.Item1.CompareTo(b.Item1);
            });


            foreach (var pair in tagsInOrder)
            {
                var tagElement = new TagUIElement(this.Manager, this);
                tagElement.TagExpander.Header = pair.Item2;

                foreach (var command in this.Manager.Commands.Values)
                {
                    foreach (var tag in command.Keywords)
                    {
                        if (tag == pair.Item2)
                        {
                            var commandElement = new CommandUIElement(command, this);
                            commandElement.CommandName.Text = command.Name;
                            tagElement.Commands.Items.Add(commandElement);
                        }
                    }
                }

                this.Tags.Items.Add(tagElement);
            }
        }

        private void Commands_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                var element = (CommandUIElement)this.Commands.SelectedItem;

                if (element != null)
                {
                    this.Manager.ExecuteRemoteCommand(element.Source.Name);
                    this.Close();
                }
            }
            else if (e.Key == Key.Escape)
            {
                this.Close();
            }
        }

        private void Search_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Down || (e.Key == Key.Right && this.Search.SelectionStart == this.Search.Text.Length))
            {
                this.Commands.Focus();
            }
        }
    }
}
